package com.ttn.student.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ttn.common.core.entity.Result;
import com.ttn.common.core.entity.business.CourseUnitVocabulary;
import com.ttn.common.core.entity.studentrecord.LearningProgressRecord;
import com.ttn.common.core.entity.studentrecord.TestStudyRecord;
import com.ttn.common.core.entity.studentrecord.VocabularyStudyRecordDetails;
import com.ttn.common.core.entity.studentrecord.bo.SaveBatchTestStudyRecordDetailsBO;
import com.ttn.common.core.entity.studentrecord.query.TestStudyRecordQuery;
import com.ttn.common.core.entity.studentrecord.vo.TestStudyRecordDetailsVO;
import com.ttn.common.core.entity.studentrecord.vo.TestStudyRecordVO;
import com.ttn.student.mapper.VocabularyStudyRecordDetailsMapper;
import com.ttn.student.service.LearningProgressRecordService;
import com.ttn.student.service.TestStudyRecordService;
import com.ttn.student.service.VocabularyStudyRecordDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class VocabularyStudyRecordDetailsServiceImpl extends ServiceImpl<VocabularyStudyRecordDetailsMapper, VocabularyStudyRecordDetails> implements VocabularyStudyRecordDetailsService {
    @Resource
    private VocabularyStudyRecordDetailsMapper vocabularyStudyRecordDetailsMapper;
    @Resource
    private TestStudyRecordService testStudyRecordService;
    @Resource
    private LearningProgressRecordService learningProgressRecordService;


    @Override
    @Transactional
    public Result saveVocabularyStudyRecordDetails(VocabularyStudyRecordDetails vocabularyStudyRecordDetails) {
        TestStudyRecordDetailsVO testStudyRecordDetailsVO = new TestStudyRecordDetailsVO();
        if (vocabularyStudyRecordDetails.getAnswer().equals(vocabularyStudyRecordDetails.getUserAnswer())) {
            vocabularyStudyRecordDetails.setAnswerFlag(1);
        } else {
            vocabularyStudyRecordDetails.setAnswerFlag(0);
        }
        this.save(vocabularyStudyRecordDetails);
        TestStudyRecord testStudyRecord = testStudyRecordService.getById(vocabularyStudyRecordDetails.getStudyRecordId());
        LambdaQueryWrapper<VocabularyStudyRecordDetails> vocabularyStudyRecordDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vocabularyStudyRecordDetailsLambdaQueryWrapper.eq(VocabularyStudyRecordDetails::getStudyRecordId, vocabularyStudyRecordDetails.getStudyRecordId());
        //保存答题数量
        Integer studyNum = Math.toIntExact(this.count(vocabularyStudyRecordDetailsLambdaQueryWrapper));
        testStudyRecord.setStudyNum(studyNum);
        testStudyRecordService.updateById(testStudyRecord);
        if (studyNum.equals(testStudyRecord.getCourseUnitNum())) {
            //获取答对题目数
            LambdaQueryWrapper<VocabularyStudyRecordDetails> vocabularyStudyRecordDetailsLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            vocabularyStudyRecordDetailsLambdaQueryWrapper1.eq(VocabularyStudyRecordDetails::getAnswerFlag, 1);
            vocabularyStudyRecordDetailsLambdaQueryWrapper1.eq(VocabularyStudyRecordDetails::getStudyRecordId, vocabularyStudyRecordDetails.getStudyRecordId());
            Long correctAnswer = this.count(vocabularyStudyRecordDetailsLambdaQueryWrapper1);
            testStudyRecord.setCorrectAmount(Math.toIntExact(correctAnswer));
            correctAnswer = correctAnswer * 100;
            testStudyRecord.setScore(NumberUtil.div(correctAnswer, testStudyRecord.getCourseUnitNum()).intValue());
            LambdaQueryWrapper<TestStudyRecord> testStudyRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //获取所有用户数量
            testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getUnitTaskType, "1");
            testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getCourseUnitId, vocabularyStudyRecordDetails.getCourseUnitId());
            long countAll = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper);
            if (countAll != 0) {
                //获取超过的用户
                testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getFinishFlag, 1);
                testStudyRecordLambdaQueryWrapper.gt(TestStudyRecord::getScore, testStudyRecord.getScore());
                long beyondProportionNum = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper);
                //更新得分和排名
                testStudyRecord.setBeyondProportion(BigDecimal.valueOf(NumberUtil.mul(NumberUtil.sub(1, NumberUtil.div(beyondProportionNum, countAll, 2)), 100)));
            } else {
                testStudyRecord.setBeyondProportion(BigDecimal.valueOf(100));
            }
            testStudyRecordDetailsVO.setTestStudyRecord(testStudyRecord);
            //获取词汇错题集
            vocabularyStudyRecordDetailsLambdaQueryWrapper.eq(VocabularyStudyRecordDetails::getAnswerFlag, 0);
            testStudyRecordDetailsVO.setVocabularyStudyRecordDetails(this.list(vocabularyStudyRecordDetailsLambdaQueryWrapper));
            testStudyRecord.setFinishFlag(1);
            testStudyRecordService.updateById(testStudyRecord);
            LambdaQueryWrapper<LearningProgressRecord> learningProgressRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            learningProgressRecordLambdaQueryWrapper.eq(LearningProgressRecord::getStudentId, testStudyRecord.getStudentId());
            learningProgressRecordLambdaQueryWrapper.eq(LearningProgressRecord::getCourseUnitId, testStudyRecord.getCourseUnitId());
            LearningProgressRecord learningProgressRecord = learningProgressRecordService.getOne(learningProgressRecordLambdaQueryWrapper);
            learningProgressRecord.setCorrectAmount(testStudyRecordService.queryTotalCorrectAmountByUnitIdId(testStudyRecord.getCourseUnitId(), testStudyRecord.getStudentId()));

            learningProgressRecordService.updateById(learningProgressRecord);
            return Result.success(testStudyRecordDetailsVO);
        }
        return Result.success();
    }

    @Override
    public Result queryVocabularyStudyRecordDetails(TestStudyRecordQuery testStudyRecordQuery) {
        //获取分数最高的一次测试记录
        TestStudyRecordDetailsVO testStudyRecordDetailsVO = new TestStudyRecordDetailsVO();
        LambdaQueryWrapper<TestStudyRecord> testStudyRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getStudentId, testStudyRecordQuery.getStudentId());
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getCourseUnitId, testStudyRecordQuery.getCourseUnitId());
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getUnitTaskType, "1");
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getFinishFlag, 1);
        testStudyRecordLambdaQueryWrapper.orderByDesc(TestStudyRecord::getScore);
        testStudyRecordLambdaQueryWrapper.last(" limit 1");
        TestStudyRecord testStudyRecord = testStudyRecordService.getOne(testStudyRecordLambdaQueryWrapper);
        if (Objects.nonNull(testStudyRecord)) {
            LambdaQueryWrapper<TestStudyRecord> testStudyRecordLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            //获取所有用户数量
            testStudyRecordLambdaQueryWrapper1.eq(TestStudyRecord::getUnitTaskType, "1");
            testStudyRecordLambdaQueryWrapper1.eq(TestStudyRecord::getCourseUnitId, testStudyRecordQuery.getCourseUnitId());
            long countAll = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper1);
            if (countAll != 0) {
                //获取超过的用户
                testStudyRecordLambdaQueryWrapper1.eq(TestStudyRecord::getFinishFlag, 1);
                testStudyRecordLambdaQueryWrapper1.gt(TestStudyRecord::getScore, testStudyRecord.getScore());
                long beyondProportionNum = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper1);
                //更新得分和排名
                testStudyRecord.setBeyondProportion(BigDecimal.valueOf(NumberUtil.mul(NumberUtil.sub(1, NumberUtil.div(beyondProportionNum, countAll, 2)), 100)));
            } else {
                testStudyRecord.setBeyondProportion(BigDecimal.valueOf(100));
            }
            testStudyRecordDetailsVO.setTestStudyRecord(testStudyRecord);
            LambdaQueryWrapper<VocabularyStudyRecordDetails> vocabularyStudyRecordDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            vocabularyStudyRecordDetailsLambdaQueryWrapper.eq(VocabularyStudyRecordDetails::getStudyRecordId,
                    testStudyRecord.getId());
            vocabularyStudyRecordDetailsLambdaQueryWrapper.eq(VocabularyStudyRecordDetails::getAnswerFlag, 0);
            testStudyRecordDetailsVO.setVocabularyStudyRecordDetails(this.list(vocabularyStudyRecordDetailsLambdaQueryWrapper));
        }

        return Result.success(testStudyRecordDetailsVO);
    }

    @Override
    public Result saveBatchVocabularyStudyRecordDetails(SaveBatchTestStudyRecordDetailsBO saveBatchVocabularyStudyRecordDetailsBO) {
        TestStudyRecordVO testStudyRecordVO = new TestStudyRecordVO();
        TestStudyRecord testStudyRecord = saveBatchVocabularyStudyRecordDetailsBO.getTestStudyRecord();
        testStudyRecordService.save(testStudyRecord);
        AtomicReference<Integer> correctAnswerAtomic = new AtomicReference<>(0);
        saveBatchVocabularyStudyRecordDetailsBO.getVocabularyStudyRecordDetails().stream().forEach(vocabularyStudyRecordDetails -> {
            if (vocabularyStudyRecordDetails.getAnswer().equals(vocabularyStudyRecordDetails.getUserAnswer())) {
                vocabularyStudyRecordDetails.setAnswerFlag(1);
                correctAnswerAtomic.getAndSet(correctAnswerAtomic.get() + 1);
            }
            vocabularyStudyRecordDetails.setStudyRecordId(testStudyRecord.getId());
            vocabularyStudyRecordDetails.setCourseUnitId(testStudyRecord.getCourseUnitId());
        });
        this.saveBatch(saveBatchVocabularyStudyRecordDetailsBO.getVocabularyStudyRecordDetails());
        LambdaUpdateWrapper<TestStudyRecord> testStudyRecordLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        testStudyRecordLambdaUpdateWrapper.eq(TestStudyRecord::getId, testStudyRecord.getId());
        //保存答题数量
        testStudyRecordLambdaUpdateWrapper.set(TestStudyRecord::getStudyNum, saveBatchVocabularyStudyRecordDetailsBO.getVocabularyStudyRecordDetails().size());
        Double score = NumberUtil.div(correctAnswerAtomic.get() * 100, saveBatchVocabularyStudyRecordDetailsBO.getVocabularyStudyRecordDetails().size());
        //更新得分

        testStudyRecordLambdaUpdateWrapper.set(TestStudyRecord::getCorrectAmount, correctAnswerAtomic.get());
        testStudyRecordLambdaUpdateWrapper.set(TestStudyRecord::getScore, score.intValue());
        //排名
        LambdaQueryWrapper<TestStudyRecord> testStudyRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取所有用户数量
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getCourseUnitId, testStudyRecord.getCourseUnitId());
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getFinishFlag, 1);
        long countAll = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper);
        if (countAll != 0) {
            //获取超过的用户
            testStudyRecordLambdaQueryWrapper.gt(TestStudyRecord::getScore, score.intValue());
            long beyondProportionNum = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper);
            testStudyRecordLambdaUpdateWrapper.set(TestStudyRecord::getBeyondProportion, NumberUtil.mul(NumberUtil.sub(1, NumberUtil.div(beyondProportionNum, countAll, 2)), 100));
        } else {
            testStudyRecordLambdaUpdateWrapper.set(TestStudyRecord::getBeyondProportion, 100);
        }

        testStudyRecordService.update(testStudyRecordLambdaUpdateWrapper);
        testStudyRecordVO.setTestStudyRecord(testStudyRecordService.getById(testStudyRecord.getId()));
        //获取词汇错题集
        LambdaQueryWrapper<VocabularyStudyRecordDetails> vocabularyStudyRecordDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vocabularyStudyRecordDetailsLambdaQueryWrapper.eq(VocabularyStudyRecordDetails::getStudyRecordId, testStudyRecord.getId());
        vocabularyStudyRecordDetailsLambdaQueryWrapper.eq(VocabularyStudyRecordDetails::getAnswerFlag, 0);
//        testStudyRecordVO.setVocabularyStudyRecordDetails(this.list(vocabularyStudyRecordDetailsLambdaQueryWrapper));
        return Result.success(testStudyRecordVO);
    }

    @Override
    public List<CourseUnitVocabulary> getUnfinishedCourseUnitVocabularyList(TestStudyRecord testStudyRecord) {
        return vocabularyStudyRecordDetailsMapper.getUnfinishedCourseUnitVocabularyList(testStudyRecord);
    }
}
